<template>
  <div class="massMsg">
    <div class="select_type">
      <div class="typelist">
        <div :style="{left: (sendType * 100) + 'px'}" class="active_box"></div>
        <div class="type_item" :class="{active: sendType == 0}" @click="sendType = 0">按用户发送</div>
        <div class="type_item" :class="{active: sendType == 1}" @click="sendType = 1">按条件发送</div>
        <div class="type_item" :class="{active: sendType == 2}" @click="sendType = 2">随机发送</div>
      </div>
    </div>
    <Split class="massbox" v-model="split">
      <div slot="left" class="left demo-split-pane">
        <div slot="left" class="left demo-split-pane">
            <div class="tops">
              已选择 {{select.length}} 个用户
              <span @click="allSelectMass">{{isAllMass() ? '取消' : '全选'}}</span>
            </div>
            <div class="cont">
              <div class="list">
                <Collapse v-model="collapse">
                 <Panel name="3">
                    消息列表<Checkbox :value="isAllSelect(3)" @click.native.stop="massAllSelect(3)"></Checkbox>
                    <div slot="content">
                      <!-- <userItem @click.native="clickUser(index)" v-if="item.subscribe && item.groupid == 1" :user="item" :index="index" v-for="(item, index) in list.userlist" :key="index"/> -->
                      <div class="item" @click="addMassUser(item.openid)" :class="{active: select.indexOf(item.openid) !== -1}" v-for="(item, index) in msguser" :key="index">
                        <div class="img"><img :src="item.headimgurl" alt=""></div>
                        <div class="name">{{item.name || item.nickname}}</div>
                        <div class="radio"><Icons name="zhengque" /></div>
                      </div>
                    </div>
                  </Panel>
                  <Panel name="1">
                    已沟通<Checkbox :value="isAllSelect(1)" @click.native.stop="massAllSelect(1)"></Checkbox>
                    <div slot="content">
                      <!-- <userItem @click.native="clickUser(index)" v-if="item.subscribe && item.groupid == 1" :user="item" :index="index" v-for="(item, index) in list.userlist" :key="index"/> -->
                      <div class="item" @click="addMassUser(item.openid)" v-if="item.subscribe && item.groupid == 1" :class="{active: select.indexOf(item.openid) !== -1}" v-for="(item, index) in userlist" :key="index">
                        <div class="img"><img :src="item.headimgurl" alt=""></div>
                        <div class="name">{{item.name || item.nickname}}</div>
                        <div class="radio"><Icons name="zhengque" /></div>
                      </div>
                    </div>
                  </Panel>
                  <Panel name="2">
                    未沟通<Checkbox :value="isAllSelect(0)" @click.native.stop="massAllSelect(0)"></Checkbox>
                    <div slot="content">
                      <!-- <userItem @click.native="clickUser(index)" v-if="item.subscribe && item.groupid == 1" :user="item" :index="index" v-for="(item, index) in list.userlist" :key="index"/> -->
                      <div class="item" @click="addMassUser(item.openid)" v-if="item.subscribe && item.groupid != 1" :class="{active: select.indexOf(item.openid) !== -1}" v-for="(item, index) in userlist" :key="index">
                        <div class="img"><img :src="item.headimgurl" alt=""></div>
                        <div class="name">{{item.name || item.nickname}}</div>
                        <div class="radio"><Icons name="zhengque" /></div>
                      </div>
                    </div>
                  </Panel>
                </Collapse>
              </div>
            </div>
            <div class="foot"></div>
        </div>
      </div>
      <div slot="right" class="right demo-split-pane">
        <div class="content">
          <div class="list">
            <Alert type="warning" v-if="msg.length === 0">
            <center>没有消息，点击下方按钮添加消息</center>
            </Alert>
            <div class="item" :type="item.type" v-for="(item, index) in msg" :key="index">
              <div @click="delMsg(index)" class="close">&times;</div>
              <div v-if="item.type !== 'outline'" @click="editMsg(index)" class="edit"><Icon type="md-create" /></div>
              <div class="textcont" v-html="item.html" v-if="item.type == 'text'"></div>
              <img :src="item.content | formatPicPath" alt="" v-else-if="item.type == 'image'">
              <span v-else-if="item.type == 'outline'">发送对应客服的离线回复</span>
            </div>
          </div>
          <div class="addmsg">
            <div @click="addMsg('text')" class="item"><Icon type="md-add" />文本</div>
            <div @click="addMsg('image')" class="item"><Icon type="md-add" />图片</div>
            <div @click="addMsg('outline')" class="item"><Icon type="md-add" />离线回复</div>
          </div>
          <Modal @on-ok="addTextdone" title="设置文本消息" class="settextmsg" v-model="settextmsg.show" width="360">
            <div class="tools">
              <Poptip placement="top-start">
                <Tooltip :transfer="true" placement="top" content="表情">
                <div class="item"><Icons name="xiaolian" /></div>
                </Tooltip>
                <div slot="content" class="facelist">
                  <div class="img" v-for="(item, index) in facelist" :key="index">
                    <img :src="item.url" @click="addFace(index)">
                    <!--  @click="addFace(index)" -->
                  </div>
                </div>
              </Poptip>
            </div>
            <div class="input">
              <editor ref="editor" class="editor" :nochat="true" v-model="settextmsg.text" @onchange="changeTexMsg"/>
            </div>
          </Modal>
        </div>
        <div class="button">
          <button class="clear" @click="closeMassbox">取消发送</button>
          <button class="start" @click="startMassmsg">开始群发</button>
        </div>
      </div>
    </Split>
  </div>
</template>

<script>
  import editor from '../editor'
  import facelist from '../../assets/data/face.json'
  export default {
    name: 'massMsg',
    data () {
      return {
        sendType: 0,
        split: 0.3,
        facelist: facelist,
        edittext: null,
        settextmsg: {
          show: false,
          text: '',
          html: ''
        },
        collapse: [3, 1, 2],
        show: false,
        select: [],
        msg: [
        ],
        sending: false,
        sendstatus: {}
      }
    },
    props: {
      csuser: {
        default: {}
      },
      userlist: {
        default: []
      },
      msguser: {
        default: []
      }
    },
    components: {
      editor
    },
    created () {
    },
    methods: {
      addface () {
        this.$refs['inputss'].insertHTML('<img class="face" src="http://crm.wqc.so/assets/expression/3.gif" alt="[发呆]" />')
      },
      sendTextMsg (data, html) {
        console.log(data)
        console.log(html)
      },
      /**
       * 添加群发的目标用户
       */
      addMassUser (openid) {
        if (this.select.indexOf(openid) !== -1) {
          this.select.splice(this.select.indexOf(openid), 1)
        } else {
          this.select.push(openid)
        }
      },
      /**
       * 全选群发用户
       */
      allSelectMass () {
        if (this.isAllMass()) {
          this.select = []
        } else {
          this.userlist.forEach((item) => {
            if (item.subscribe) {
              if (this.select.indexOf(item.openid) === -1) {
                this.select.push(item.openid)
              }
            }
          })
        }
      },
      /**
       * 判断是否全选群发用户
       */
      isAllMass () {
        var isAll = true
        this.userlist.forEach((item) => {
          if (item.subscribe) {
            if (this.select.indexOf(item.openid) === -1) {
              isAll = false
            }
          }
        })
        return isAll
      },
      /**
       * 分组是否全选
       */
      isAllSelect (type) {
        var result = true
        if (type === 3) {
          this.msguser.forEach((item) => {
            if (this.select.indexOf(item.openid) === -1) {
              result = false
            }
          })
        } else {
          this.userlist.forEach((item) => {
            if (type === 1) {
              if (item.subscribe && item.groupid) {
                if (this.select.indexOf(item.openid) === -1) {
                  result = false
                }
              }
            } else if (type === 0) {
              if (item.subscribe && !item.groupid) {
                if (this.select.indexOf(item.openid) === -1) {
                  result = false
                }
              }
            }
          })
        }
        return result
      },
      /**
       * 全选分组
       */
      massAllSelect (type) {
        var inGroup = this.isAllSelect(1)
        var inUnGroup = this.isAllSelect(0)
        var inMsgList = this.isAllSelect(3)
        if (type === 3) {
          console.log('消息列表', inMsgList ? '取消全选' : '全选')
          this.msguser.forEach((item) => {
            console.log(123213)
            if (inMsgList) {
              this.select.splice(this.select.indexOf(item.openid), 1)
            } else {
              if (this.select.indexOf(item.openid) === -1) {
                console.log('不在选中，添加')
                this.select.push(item.openid)
              }
            }
          })
        } else {
          this.userlist.forEach((item) => {
            if (type === 1) {
              if (item.subscribe && item.groupid) {
                if (inGroup) {
                  this.select.splice(this.select.indexOf(item.openid), 1)
                } else {
                  if (this.select.indexOf(item.openid) === -1) {
                    this.select.push(item.openid)
                  }
                }
              }
            } else {
              if (item.subscribe && !item.groupid) {
                if (inUnGroup) {
                  this.select.splice(this.select.indexOf(item.openid), 1)
                } else {
                  if (this.select.indexOf(item.openid) === -1) {
                    this.select.push(item.openid)
                  }
                }
              }
            }
          })
        }
        console.log(this.select)
      },
      // 关闭
      closeMassbox () {
        this.$emit('closeMassbox')
      },
      // 编辑消息
      editMsg (index) {
        if (this.msg[index].type === 'image') {
          var input = document.createElement('input')
          input.setAttribute('type', 'file')
          var _this = this
          input.onchange = async function () {
            _this.$Message.loading({
              content: '上传中',
              uration: 0
            })
            try {
              var datas = {
                appid: _this.csuser.appid,
                type: 'image',
                file: this.files[0]
              }
              var result = await _this.$fn.getMediaId(datas)
              console.log(result)
              _this.$Message.destroy()
              if (result.status === 1) {
                _this.$Message.success('上传成功')
                _this.msg.push({
                  type: 'image',
                  content: result.path,
                  media_id: result.media_id
                })
              } else {
                throw new Error('上传失败')
              }
            } catch (e) {
              console.log(e)
              _this.$Message.error('上传失败')
            }
          }
          input.click()
        } else if (this.msg[index].type === 'text') {
          this.edittext = index
          this.$refs['editor'].clearContent()
          setTimeout(() => {
            this.$refs['editor'].insertHTML(this.msg[index].html)
          }, 10)
          this.settextmsg.show = true
        }
      },
      // 删除消息
      delMsg (index) {
        console.log(index)
        this.msg.splice(index, 1)
      },
      // 添加消息
      addMsg (type) {
        if (type === 'outline') {
          this.msg.push({
            type: 'outline'
          })
        } else if (type === 'text') {
          this.settextmsg.show = true
        } else if (type === 'image') {
          // https://a.yougou520.cn/api/Upload/upload
          var input = document.createElement('input')
          input.setAttribute('type', 'file')
          var _this = this
          input.onchange = async function () {
            _this.$Message.loading({
              content: '上传中',
              uration: 0
            })
            try {
              console.log(_this.csuser)
              var datas = {
                appid: _this.csuser.appid,
                type: 'image',
                file: this.files[0]
              }
              var result = await _this.$fn.getMediaId(datas)
              console.log(result)
              _this.$Message.destroy()
              if (result.status === 1) {
                _this.$Message.success('上传成功')
                _this.msg.push({
                  type: 'image',
                  content: result.path,
                  media_id: result.media_id
                })
              } else {
                throw new Error('上传失败')
              }
            } catch (e) {
              console.log(e)
              _this.$Message.error('上传失败')
            }
          }
          input.click()
        }
      },
      // 编辑文本消息
      changeTexMsg (text, html) {
        this.settextmsg.text = text
        this.settextmsg.html = html
        console.log(this.settextmsg)
      },
      // 添加表情到输入框
      addFace (index) {
        this.$refs['editor'].insertHTML('<img class="face" src="' + this.facelist[index].url + '" alt="' + this.facelist[index].value + '" />')
      },
      // 文本编辑确定
      addTextdone () {
        if (this.edittext !== null) {
          this.msg.splice(this.edittext, 1, {
            type: 'text',
            text: this.settextmsg.text,
            html: this.settextmsg.html
          })
          this.$refs['editor'].clearContent()
          this.edittext = null
          return
        }
        this.msg.push({
          type: 'text',
          text: this.settextmsg.text,
          html: this.settextmsg.html
        })
        this.$refs['editor'].clearContent()
      },
      // 开始群发消息
      startMassmsg () {
        if (this.select.length === 0) {
          this.$Message.error('至少选择一个发送对象')
          return
        }
        if (this.msg.length === 0) {
          this.$Message.error('至少添加一条消息')
          return
        }
        var data = {
          csuser: this.csuser,
          msglist: this.msg,
          userlist: this.select
        }
        this.$electron.ipcRenderer.send('send_mass_msg', JSON.parse(JSON.stringify(data)))
        this.closeMassbox()
      }
    }
  }
</script>

<style lang="less">
  @import './style.less';
</style>
